<template>
  <div class="dashboard-container">
    <div class="title">发电企业科目余额看板</div>
    <div class="chart-container">
      <div v-has-perm="['nljs_dashboard_income_cost']" class="chart-item">
        <h3>收入/成本比TOP10（期末余额）</h3>
        <!-- <div class="income-form"> -->
        <el-row :gutter="15" class="row-item">
          <el-col :span="12" class="inline">
            <div class="label">时间范围</div>
            <el-date-picker
              key="date1"
              v-model="timeRange"
              class="dates"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM"
              value-format="YYYY-MM-DD"
              @change="handleTimeChange"
            />
          </el-col>
          <el-col :span="12" class="inline">
            <div class="label">区域</div>
            <el-select
              v-model="areaIds"
              class="selector"
              multiple
              collapse-tags
              clearable
              @change="handleRegionChange"
            >
              <el-option
                v-for="region in areaList"
                :key="region.id"
                :label="region.name"
                :value="region.id"
              />
            </el-select>
          </el-col>
        </el-row>
        <!-- </div> -->

        <ECharts
          key="e1"
          :options="topOptions"
          height="420px"
          class="charts"
          @clickChart="clickChart1"
        />
      </div>

      <div v-has-perm="['nljs_dashboard_income_cost']" class="chart-item">
        <h3>企业多维指标趋势分析（期末余额）</h3>
        <el-row class="row-item">
          <el-col :span="14" class="inline">
            <div class="mlabel">时间范围</div>
            <div class="date-container">
              <el-date-picker
                key="date2"
                v-model="mtimeRange"
                type="monthrange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
                @change="handleTimeChangem"
              />
            </div>
          </el-col>
          <el-col :span="10" class="inline">
            <div class="mlabel2">指标</div>
            <el-select
              v-model="selectedMetrics"
              placeholder="选择指标"
              multiple
              filterable
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              @change="handleMetricsChange"
            >
              <el-option
                v-for="metric in metricOptions"
                :key="metric.value"
                :label="metric.label"
                :value="metric.value"
              />
            </el-select>
          </el-col>
          <el-col :span="14" class="inline inline2">
            <div class="mlabel">企业</div>
            <select-tree ref="selectTreeRef" width="calc(100% - 110px)"
              v-model="selectedCompany"
              :data="unitOptions"
              :props="{
                label: 'name',
                value: 'id',
                children: 'children',
              }"
              :closeOnCheck="true" placeholder="" :show-checkbox="false"
              :expand-on-click-node="false" :check-on-click-node="true" :collapse-tags="true"
              :check-strictly="true" @nodeClick="nodeClick">
            </select-tree>
            <!-- <el-tree-select
              v-model="selectedCompany"
              :check-strictly="true"
              :data="unitOptions"
              node-key="id"
              :props="{
                label: 'name',
                children: 'children',
              }"
              :render-after-expand="false"
              @current-change="nodeClick"
            >
              <template #default="scope">
                <span :title="scope.data.name">{{ scope.data.name }}</span>
              </template>
            </el-tree-select> -->
          </el-col>
          <el-col :span="10" class="inline inline2">
            <div class="mlabel2">是否查询下级所有单位</div>
            <el-switch v-model="includeSubordinates" @change="getMultiData"/>
          </el-col>
        </el-row>
        <ECharts
          key="e2"
          ref="charts2"
          :options="multiOptions"
          height="400px"
          class="charts"
          @clickChart="clickChart2"
        />
      </div>
    </div>

    <el-dialog v-model="dialogTableVisible" title="指标数据" width="600">
      <el-table :data="metricData">
        <el-table-column type="index" label="序号" width="90" />
        <el-table-column property="metric" label="指标名称" width="200" />
        <el-table-column property="value" label="金额（万元）" width="200" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import type { EChartsOption } from 'vchart';
import DeptAPI from '@/api/system/dept.api';
import UnitAPI from '@/api/system/unit.api';
import MonitorAPI from '@/api/monitor/monitor.api';
import {
  getCurrentDateFormatted,
  getMonthsAgoFormatted,
  getMonthStartAndEnd,
  getMonthEndDay,
} from '@/utils/date';
import SelectTree from '@/components/SelectTree/index.vue';

// 数据模型定义
interface CompanyData {
  name: string;
  businessIncome: number;
  nonBusinessIncome: number;
  businessCost: number;
  nonBusinessExpense: number;
  region: string;
}

// picker-options 配置
const disabledDate = (time: any) => {
  const futureLimit = new Date();
  futureLimit.setDate(futureLimit.getDate() + 30); // 允许未来30天
  return time.getTime() > futureLimit;
  // 方案一：禁用所有未来日期（含当天之后的时间）
  // return time.getTime() > Date.now();

  // 方案二：允许当天日期（即使时间已过）
  // const todayStart = new Date().setHours(0, 0, 0, 0);
  // return time.getTime() > todayStart;
};
const timeRange = ref<any[]>([]);
const mtimeRange = ref<any[]>([]);
const areaIds = ref<string[]>([]);
const unitOptions = ref<any>([]);
const selectedCompany = ref<any[]>([]);
const includeSubordinates = ref<boolean>(true);
const selectedMetrics = ref<string[]>([
  'mainBusinessIncome',
  'otherBusinessIncome',
  'nonOperatingIncome',
]);
const companyOptions = ref<{ label: string; value: string }[]>([]);
const areaList = ref<any[]>([]);
const metricOptions = [
  { value: 'mainBusinessIncome', label: '主营业务收入' },
  { value: 'otherBusinessIncome', label: '其他业务收入' },
  { value: 'nonOperatingIncome', label: '营业外收入' },
  { value: 'businessIncome', label: '业务收入' }, // 业务收入=主营业务收入+其他业务收入
  { value: 'totalIncome', label: '总收入' }, // 总收入=业务收入+营业外收入
  { value: 'mainBusinessCost', label: '主营业务成本' },
  { value: 'otherBusinessCost', label: '其他业务成本' },
  { value: 'nonOperatingExpense', label: '营业外支出' },
  { value: 'businessCost', label: '业务成本' }, // 业务成本=主营业务成本+其他业务成本
  { value: 'totalCost', label: '总成本' }, // 总成本=业务成本+营业外支出
  { value: 'incomeCostRatio', label: '收入/成本比' }, // 收入/成本比=(总收入/总成本*100%)
  { value: 'surplus', label: '盈余' }, // 盈余=总收入-总成本
];
const indicatorsMap: any = {
  mainBusinessIncome: '主营业务收入',
  otherBusinessIncome: '其他业务收入', // 业务收入=主营业务收入+其他业务收入
  nonOperatingIncome: '营业外收入', // 业务成本=主营业务成本+其他业务成本
  businessIncome: '业务收入', // 业务收入=主营业务收入+其他业务收入
  totalIncome: '总收入', // 总收入=业务收入+营业外收入
  mainBusinessCost: '主营业务成本',
  otherBusinessCost: '其他业务成本',
  nonOperatingExpense: '营业外支出',
  businessCost: '业务成本', // 业务成本=主营业务成本+其他业务成本
  totalCost: '总成本', // 总成本=业务成本+营业外支出
  incomeCostRatio: '收入/成本比', // 收入/成本比=(总收入/总成本*100%)
  surplus: '盈余', // 盈余=总收入-总成本
};

const multiData = ref<any>([]);
const charts2 = ref<any>();
const topOptions = ref<any>({});
const multiOptions = ref<any>({});

const dialogTableVisible = ref(false);
const metricData = ref<any[]>([]);

const handleTimeChange = (val: any) => {
  console.log('val-', val);
  if (val && val.length > 0) {
    getTopData();
  }
};
const handleRegionChange = (val: any) => {
  getTopData();
};
const handleTimeChangem = (val: any) => {
  if (val && val.length > 0) {
    getMultiData();
  }
};
const nodeClick = (val: any) => {
  console.log('父nodeClick-', val.id, selectedCompany.value);
  setTimeout(() => {
    console.log('delay-', selectedCompany.value);
    if (!mtimeRange.value || !mtimeRange.value.length || !selectedCompany.value) {
      return;
    }
    getMultiData();
  }, 0);
};
const handleMetricsChange = (val: any) => {
  if (!val.length) {
    return;
  }
  getMultiData();
};

const getAreaOptions = () => {
  DeptAPI.getListAll()
    .then((data: any[]) => {
      areaList.value = data;
    })
    .catch((err) => {});
};

const initUnitList = async () => {
  const data: any = await UnitAPI.getTree();
  unitOptions.value = data;
  selectedCompany.value = data.length > 0 ? data[0].id : '';
};

const getTopData = () => {
  // {
  //   "companyId": 1,
  //   "companyName": "国电成都金堂发电有限公司",
  //   "areaId": 1,
  //   "areaName": "成都市",
  //   "batchId": 2,
  //   "batchName": "20250514001",
  //   "batchEndTime": "",
  //   "mainBusinessIncome": 5000, // 主营业务收入（科目代码：60010000）
  //   "otherBusinessIncome": 1000, // 其他业务收入（科目代码：60510000）
  //   2"nonOperatingIncome": 500, // 营业外收入（科目代码：63010000）
  //   1"businessIncome": 6000, // 业务收入（主营业务收入 + 其他业务收入）
  //   "totalIncome": 6500, // 总收入（业务收入 + 营业外收入）
  //   "mainBusinessCost": 3000, // 	主营业务成本（科目代码：64010000）
  //   "otherBusinessCost": 500, // 其他业务成本（科目代码：64020000）
  //   4"nonOperatingExpense": 200, // 	营业外支出（科目代码：67110000）
  //   3"businessCost": 3500, // 业务成本（主营业务成本 + 其他业务成本）
  //   "totalCost": 3700, // 总成本（业务成本 + 营业外支出）
  //   "incomeCostRatio": 175.68, // 收入/成本比（总收入/总成本*100%）
  //   5"surplus": 2800 // 盈余（总收入 - 总成本）
  // }
  MonitorAPI.getTopChart({
    startDate: timeRange.value[0],
    endDate: getMonthEndDay(timeRange.value[1]),
    areaIds: areaIds.value,
  })
    .then((data) => {
      initChart1(data);
    })
    .catch((err) => {});
};
const initChart1 = (data: any[]) => {
  const yDatas = data.map((item) => item.companyName);
  const sdata = data.map(
    (item) =>
      ((item.businessIncome + item.nonOperatingIncome) * 100) /
      (item.businessCost + item.nonOperatingExpense || 1)
  );
  console.log('series-', sdata);

  topOptions.value = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // Use axis to trigger tooltip
        type: 'shadow', // 'shadow' as default; can also be 'line' or 'shadow'
      },
      textStyle: {
        lineHeight: 20, // 行高（像素）
        fontSize: 14,
        extraCssText: 'min-width: 250px; padding: 10px; border-radius: 4px;',
      },
      formatter: (params: any) => {
        const obj = data.find((item) => item.companyName === params[0].name);
        return `</span>企业：${params[0].name}<br/>
                <span style="display: inline-block; width: 10px; height: 10px; background: ${params[0].color}; margin-right: 5px;"></span>
                <span>业务收入：${obj?.businessIncome}</span><br/>
                <span style="display: inline-block; width: 10px; height: 10px; background: ${params[0].color}; margin-right: 5px;"></span>
                <span>营业外收入：${obj?.nonOperatingIncome}</span><br/>
                <span style="display: inline-block; width: 10px; height: 10px; background: ${params[1].color}; margin-right: 5px;"></span>
                <span>业务成本：${obj?.businessCost}</span><br/>
                <span style="display: inline-block; width: 10px; height: 10px; background: ${params[1].color}; margin-right: 5px;"></span>
                <span>营业外支出：${obj?.nonOperatingExpense}</span><br/>
                <span style="display: inline-block; width: 10px; height: 10px; background: #8000E6; margin-right: 5px;"></span>
                盈余：${obj?.surplus}`;
      },
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      right: '5%',
      type: 'category',
      data: yDatas,
    },
    yAxis: {
      type: 'value',
      name: '收入/成本比(%)',
      axisLabel: {
        formatter: '{value}%',
      },
    },
    series: [
      {
        name: '总收入',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
        },
        emphasis: {
          focus: 'series',
        },
        // data: data.map((item) => item.totalIncome),
        data: sdata,
      },
      {
        name: '总成本',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
        },
        emphasis: {
          focus: 'series',
        },
        data: data.map((item) => item.totalCost),
      },
    ],
  };
};
const getMultiData = () => {
  MonitorAPI.getCompanyChart({
    startDate: mtimeRange.value[0],
    endDate: getMonthEndDay(mtimeRange.value[1]),
    companyId: selectedCompany.value,
    indicators: selectedMetrics.value,
    includeSubordinates: includeSubordinates.value
  })
    .then((data) => {
      multiData.value = [...data];
      // const ddd = [
      //   {
      //     companyId: 2,
      //     companyName: '国电成都金堂发电有限公司',
      //     areaId: 1,
      //     areaName: '成都市',
      //     year: 2024,
      //     month: 5,
      //     period: '2024年5月',
      //     mainBusinessIncome: 5000,
      //     otherBusinessIncome: 1000,
      //     nonOperatingIncome: 500,
      //     businessIncome: 6000,
      //     totalIncome: 6500,
      //     mainBusinessCost: 3000,
      //     otherBusinessCost: 500,
      //     nonOperatingExpense: 200,
      //     businessCost: 3500,
      //     totalCost: 3700,
      //     incomeCostRatio: 175.68,
      //     surplus: 2800,
      //   },
      //   {
      //     companyId: 3,
      //     companyName: '中国国电集团有限公司成都热电厂',
      //     areaId: 1,
      //     areaName: '成都市',
      //     year: 2024,
      //     month: 5,
      //     period: '2024年4月',
      //     mainBusinessIncome: 5000,
      //     otherBusinessIncome: 1000,
      //     nonOperatingIncome: 500,
      //     businessIncome: 6000,
      //     totalIncome: 6500,
      //     mainBusinessCost: 3000,
      //     otherBusinessCost: 500,
      //     nonOperatingExpense: 200,
      //     businessCost: 3500,
      //     totalCost: 3700,
      //     incomeCostRatio: 175.68,
      //     surplus: 2800,
      //   },
      //   {
      //     companyId: 4,
      //     companyName: '国家能源投资集团有限责任公司成都热电厂',
      //     areaId: 1,
      //     areaName: '成都市',
      //     year: 2024,
      //     month: 5,
      //     period: '2024年4月',
      //     mainBusinessIncome: 5000,
      //     otherBusinessIncome: 1000,
      //     nonOperatingIncome: 500,
      //     businessIncome: 6000,
      //     totalIncome: 6500,
      //     mainBusinessCost: 3000,
      //     otherBusinessCost: 500,
      //     nonOperatingExpense: 200,
      //     businessCost: 3500,
      //     totalCost: 3700,
      //     incomeCostRatio: 175.68,
      //     surplus: 2800,
      //   },
      // ];
      initChart2(data);
    })
    .catch((err) => {});
};

const initChart2 = (data: any[]) => {
  const xDatas = data.map((item) => item.period);
  const seriesArr: any[] = [];
  const legendData: any[] = [];

  const averageArr: any = [];
  for (let i = 0; i < data.length; i++) {
    let average: any = 0;
    for (let j = 0; j < selectedMetrics.value.length; j++) {
      average += data[i][selectedMetrics.value[j]];
    }
    average = (average / selectedMetrics.value.length).toFixed(2);
    averageArr.push(average);
  }

  selectedMetrics.value.forEach((indicator) => {
    const seriesData = data.map((item) => item[indicator]);
    legendData.push(indicatorsMap[indicator]);
    const series = {
      name: indicatorsMap[indicator],
      type: 'bar',
      tooltip: {
        valueFormatter: function (value: any) {
          return value + ' 万元';
        },
      },
      data: seriesData,
    };
    seriesArr.push(series);
  });

  seriesArr.push({
    name: '均值',
    type: 'line',
    tooltip: {
      valueFormatter: function (value: any) {
        return value + ' 万元';
      },
    },
    markLine: {
      data: [{ type: 'average', name: '均值' }],
      symbol: ['none', 'none'],
      position: 'insideTopCenter',
      itemStyle: {
        normal: {
          lineStyle: {
            type: 'dotted',
            color: 'red',
          },
          label: {
            show: true,
            position: 'middle',
            formatter: '数据平均 : ' + '均值',
          },
        },
      },
      large: true,
      effect: {
        show: false,
        loop: true,
        period: 0,
        scaleSize: 2,
        color: null,
        shadowColor: null,
        shadowBlur: null,
      },
    },
    data: averageArr,
  });
  console.log('seriesArr-', seriesArr);

  multiOptions.value = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    // toolbox: {
    //   feature: {
    //     dataView: { show: true, readOnly: false },
    //     magicType: { show: true, type: ['line', 'bar'] },
    //     restore: { show: true },
    //     saveAsImage: { show: true },
    //   },
    // },
    legend: {
      data: legendData,
    },
    xAxis: [
      {
        type: 'category',
        data: xDatas,
        axisPointer: {
          type: 'shadow',
        },
      },
    ],
    yAxis: {
      type: 'value',
      // name: 'Precipitation',
      // min: 0,
      // max: 250,
      // interval: 50,
      axisLabel: {
        formatter: '{value} 万元',
      },
    },
    series: seriesArr,
  };
  // const mainBusinessIncomeData = data.map((item) => item.mainBusinessIncome);
};

const clickChart1 = (params: any) => {
  // console.log('params1-', params);
  const { seriesName, name, dataIndex, value } = params;
};
const clickChart2 = (params: any) => {
  // console.log('params2-', params);
  // seriesName-系列名称 name-x轴 dataIndex-数据索引
  const { seriesName, name, dataIndex, value } = params;
  dialogTableVisible.value = true;

  const cur = multiData.value.find((item: any) => item.period === name);
  console.log('cur-', cur);

  metricData.value = [];
  metricOptions.forEach((item) => {
    metricData.value.push({
      metric: item.label,
      value: cur[item.value],
    });
  });
};

onBeforeMount(() => {
  let startDate = getMonthStartAndEnd(getMonthsAgoFormatted(3)).firstDay;
  let endDate = getMonthStartAndEnd(getCurrentDateFormatted()).lastDay;
  timeRange.value = [startDate, endDate];
  mtimeRange.value = [startDate, endDate];
});

onMounted(async () => {
  getAreaOptions();
  await initUnitList();
  getTopData();
  getMultiData();
});

onBeforeUnmount(() => {});

// 图表配置
const top10ChartOptions = computed<any>(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: (params) => {
      const data = params[0].data as CompanyData;
      return `企业：${data.name}<br/>
              业务收入：${data.businessIncome}<br/>
              营业外收入：${data.nonBusinessIncome}<br/>
              业务成本：${data.businessCost}<br/>
              营业外支出：${data.nonBusinessExpense}<br/>
              盈余：${
                data.businessIncome +
                data.nonBusinessIncome -
                (data.businessCost + data.nonBusinessExpense)
              }`;
    },
  },
  xAxis: {
    type: 'value',
    name: '收入/成本比(%)',
    axisLabel: {
      formatter: '{value}%',
    },
  },
  yAxis: {
    type: 'category',
    data: top10Data.value.map((item) => item.name),
  },
  series: [
    {
      name: '收入',
      type: 'bar',
      stack: 'total',
      itemStyle: { color: '#67C23A' },
      data: top10Data.value.map(
        (item) =>
          ((item.businessIncome + item.nonBusinessIncome) * 100) /
          (item.businessCost + item.nonBusinessExpense || 1)
      ),
    },
    {
      name: '成本',
      type: 'bar',
      stack: 'total',
      itemStyle: { color: '#F56C6C' },
      data: top10Data.value.map(
        (item) =>
          ((item.businessCost + item.nonBusinessExpense) * 100) /
          (item.businessCost + item.nonBusinessExpense || 1)
      ),
    },
  ],
}));
</script>

<style lang="scss" scoped>
.title {
  text-align: center;
  font-size: 22px;
  padding: 10px 0 10px;
  font-weight: 600;
}

.dashboard-container {
  padding: 20px;
}

.filter-form {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.income-form {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.row-item {
  width: 100%;
}

.inline {
  display: flex;
  align-content: center;
}
.inline2{
  margin-top: 10px;
}
.date-container{
  width: calc(100% - 110px);
}

.label {
  color: #606266;
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  margin-right: 10px;
}
.mlabel{
  color: #606266;
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  margin-right: 10px;
  width: 60px;
}
.mlabel2{
  color: #606266;
  font-size: 14px;
  height: 30px;
  line-height: 30px;
  margin-right: 10px;
  min-width: 60px;
}
.dates {
  width: 100%;
}

.selector {
  width: 220px;
}

.charts {
  margin-top: 20px;
}

.chart-container {
  width: 100%;
  display: flex;
  // display: grid;
  // grid-template-columns: 1fr 1fr;
  gap: 20px 20px;
}

.chart-item {
  width: 50%;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.chart {
  height: 400px;
}
</style>
